package com.grace.cms.general.controller.manage;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.grace.common.core.domain.AjaxResult;
import com.grace.common.utils.html.EscapeUtil;
import com.grace.cms.common.constant.OlySystemConstant;
import com.grace.cms.common.enums.ArticleTypeEnums;
import com.grace.cms.general.controller.CommonController;
import com.grace.cms.general.service.search.GeneralArticleServiceImpl;
import com.grace.cms.general.utils.WebUtils;
import com.grace.cms.query.model.param.ArticleSearchParam;
import com.grace.cms.query.model.vo.WebArticleVo;
import com.grace.cms.search.lucene.document.ArticleDocument;
import com.grace.cms.search.lucene.service.LuceneSearchService;

/**
 * 站点管理
 * 远程操作本地站点接口
 * 可在配置指定IP访问
 * 管理入口/{themeName}/manage/web
 */
@RestController
@RequestMapping("/{themeName}" + OlySystemConstant.WEB_MANAGE_URL_PREFIX)
public class WebController extends CommonController {
    @Autowired
    private LuceneSearchService luceneService;

    @Autowired
    private GeneralArticleServiceImpl  articleService;
    
    /**
     * 获取本地主题列表
     * 
     * @return
     */
    @PostMapping("/lucene/rebuild")
    public AjaxResult luceneRebuild(@PathVariable("themeName") String themeName) {
        ArticleSearchParam param = articleService.getArticleSearchParam(themeName);
        param.setUseArticleContent(true);
        List<WebArticleVo> articles = articleService.listArticleBySearch(param);
        if (articles == null || articles.isEmpty()) {
            return error("未找到可重建的文章数据!");
        }
        for (WebArticleVo article : articles) {
            ArticleDocument document=articleToDocument(article);
            try {
                luceneService.addDocument(document);
            } catch (IOException e) {
                logger.error("添加文章失败: " + e.getMessage(), e);
                return error("添加文章失败!");
            }
        }

        return success("成功重建 " + articles.size() + " 篇文章索引!");
    }

    @PostMapping("/lucene/sync")
    public AjaxResult luceneSync(@PathVariable("themeName") String themeName) {
        List<String> themeNames = WebUtils.listThemeNames();
        if (themeNames != null) {
            return success(themeNames);
        }
        return error("本地未安装任何主题!");
    }

    /**
     * 将WebArticleVo转换为ArticleDocument
     * @param webArticle WebArticleVo对象
     * @return ArticleDocument
     */
    private ArticleDocument articleToDocument(WebArticleVo webArticle) {
        if (webArticle == null) {
            return null;
        }
        ArticleDocument articleDocument = new ArticleDocument();
        articleDocument.setId(webArticle.getArticleId() != null ? webArticle.getArticleId().toString() : "");
        articleDocument.setTitle(webArticle.getArticleTitle() != null ? webArticle.getArticleTitle() : "");
        articleDocument.setContent(webArticle.getArticleType()== ArticleTypeEnums.PHOTO.ordinal()? "" : EscapeUtil.escape(webArticle.getArticleContent()));
        articleDocument.setAuthor(webArticle.getCreateBy() != null ? webArticle.getCreateBy() : "");
        articleDocument.setPublishDate(webArticle.getCreateTime().getTime());
        articleDocument.setTags(webArticle.getCategories().stream().map(category -> category.getCategoryName()).collect(Collectors.toList()));
        articleDocument.setStatus(webArticle.getVisible() != null ? webArticle.getVisible().toString() : "");
        articleDocument.setViewCount(webArticle.getArticleCount().getRecordLook() != null ? webArticle.getArticleCount().getRecordLook() : 0L);
        articleDocument.setArticleType(ArticleTypeEnums.getValueByOrdinal(webArticle.getArticleType()));
        articleDocument.setCoverImage(webArticle.getArticleImg() != null ? webArticle.getArticleImg() : "");
        articleDocument.setSummary(webArticle.getArticleSummary()!= null ? webArticle.getArticleSummary() : "");
        return articleDocument;
    }

}
